﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace VNet.VisiSuite.Controls
{
    /// <summary>
    /// Interaction logic for CountDownTimer.xaml
    /// </summary>
    public partial class CountDownTimer : UserControl
    {
        DispatcherTimer timer;
        public CountDownTimer()
        {
            InitializeComponent();
            Init();

            timer = new DispatcherTimer(new TimeSpan(0, 0, 1), DispatcherPriority.Normal, delegate
            {
                TimeSpan step = TimeSpan.FromSeconds(1);
                TimeSpan -= step;
                ttbCountDown.Text = (TimeSpan < TimeSpan.Zero ? "-" : string.Empty) + TimeSpan.ToString(@"hh\:mm");
            }, this.Dispatcher);
            timer.Stop();

        }

        private void Init()
        {
            ttbCountDown.DataContext = this;
            Loaded += new RoutedEventHandler(CountDownTimer_Loaded);
            Unloaded += new RoutedEventHandler(CountDownTimer_Unloaded);
        }

        ~CountDownTimer()
        {
            Dispose();
        }

        public void Dispose()
        {
            timer.Stop();
        }

        /// <summary>
        /// Represents the time remaining for the count down to complete.
        /// </summary>
        /// <exception cref="System.ArgumentException">
        /// </exception>
        public TimeSpan TimeSpan
        {
            get { return (TimeSpan)GetValue(TimeSpanProperty); }
            set
            {
                SetValue(TimeSpanProperty, value);
            }
        }

        public static readonly DependencyProperty TimeSpanProperty =
            DependencyProperty.Register("TimeSpan", typeof(TimeSpan), typeof(CountDownTimer), new UIPropertyMetadata(TimeSpan.Zero));

        /// <summary>
        /// Sets the time span to zero and stops the timer.
        /// </summary>
        public void Reset()
        {
            TimeSpan = TimeSpan.Zero;
        }

        void CountDownTimer_Loaded(object sender, RoutedEventArgs e)
        {
            
        }

        void CountDownTimer_Unloaded(object sender, RoutedEventArgs e)
        {
            timer.Stop();
        }

        public void StartTimer()
        {
            timer.Start();
        }

        public void StopTimer()
        {
            timer.Stop();
        }

        public void SetTimeSpan(int minutes)
        {
            Reset();
            TimeSpan = TimeSpan.FromMinutes(minutes);
        }
    }
}
